<template> 
  <div class="markdown-warp">
    <div class="left-warp">
        <div class="resize-bar" ></div>
        <div class="resize-line"></div>
        <div class="resize-save" ref="scrollWarp" @scroll="textWarpScrollHandle">
          <div class="edit-warp" ref="editWarp" :contenteditable="true" @keyup="editKeyupHandle" @paste="pasteHandle" @click="clickHandle">
            <!-- 左侧的内容，左侧的内容，左侧的内容，左侧的内容 --> 
          </div> 
        </div>                                            
    </div>
    <div class="preview-warp" ref="previewWarp" @scroll="contentWarpScrollHandle">
      
    </div>
  </div>
   
</template>

<script>
import {SERVER_HOST} from '@/constant'
import {FILE_UPLOAD} from '$my/code/api/file'
import {normalUpload} from '@/helper/updownload'
import hljs from 'highlight.js'
import marked from 'marked'
import 'highlight.js/styles/railscasts.css'
export default {
  mixins: [],
  components: {},
  props: {
    // defaultContent: {
    //   type: String,
    //   default: ''
    // }
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return { 
      content: '',
      lastRange: null
    }
  },
  computed: {
  },
  watch: {
    value(val) {  
      this.content = val
      if (this.$refs.editWarp.innerText !== val) {
        if (!this.lastRange) {
          const selection = window.getSelection() 
          this.lastRange = selection.getRangeAt(0)
          
        }
        this.$refs.editWarp.innerText = val // this.content 
        this.$nextTick(() => {  
          const newSel = window.getSelection()
          newSel.removeAllRanges()
          newSel.addRange(this.lastRange)
        }) 
        
      }  
      this.$refs.previewWarp.innerHTML = marked(this.content).replace(/<pre>/gi, '<pre class="hljs">')
      
    },
    content(val) {
      this.$emit('input', val)
    }
  },
  methods: {
    clickHandle(e) { 
      const selection = window.getSelection() 
      this.lastRange = selection.getRangeAt(0)
       
    },
    editKeyupHandle(e) {
      if (this.inputTimer) {
        clearTimeout(this.inputTimer)
      }
      
      this.inputTimer = setTimeout(() => {
        this.$refs.previewWarp.innerHTML = marked(e.target.innerText).replace(/<pre>/gi, '<pre class="hljs">') 
        this.content = e.target.innerText 
 
        const selection = window.getSelection() 
        this.lastRange = selection.getRangeAt(0)
      }, 500)
    },
    pasteHandle(e) { 
      const types = e.clipboardData.types 
      const items = e.clipboardData.items
      let item = null;
      for (let i = 0; i < types.length; i++) {
        if (types[i] === 'Files') {
            item = items[i];
            break;
        }
      }
      if (item) {
        const file = item.getAsFile();
        if (/image/gi.test(file.type)) { 
          normalUpload(file, FILE_UPLOAD).then((res) => {
            this.$emit('on-imgUploaded', res)
            const selection = window.getSelection()
            this.lastRange = selection.getRangeAt(0)

            const imgStr = `\n\t![${res.id.split('@')[0]}](${SERVER_HOST}${res.id.split('@')[1].replace(/\\/g, '/')})\n\t` 
            this.insertContent(imgStr) 
          })
          e.preventDefault();
        }
      }
    },
    insertContent(str, type = 'image') {
      this.$refs.editWarp.focus() 
      let addRange = null 
       
      if (this.lastRange) { 
        addRange = this.lastRange
      } else {
         
        const selection = window.getSelection() 
        selection.selectAllChildren(this.$refs.editWarp)
        selection.collapseToEnd() 
        addRange = selection.getRangeAt(0)
      } 

      
      const textNode = document.createTextNode(str)
      if (type === 'image') {
        const blockNode = document.createElement('DIV')
        blockNode.classList.add('img-text')
        blockNode.appendChild(textNode)  
        addRange.insertNode(blockNode)
        addRange.insertNode(document.createElement('DIV'))
      } else {
        addRange.insertNode(textNode) 
      }
      

      this.$nextTick(() => {
        this.$refs.previewWarp.innerHTML = marked(this.$refs.editWarp.innerText).replace(/<pre>/gi, '<pre class="hljs">') 
        this.content = this.$refs.editWarp.innerText
      }) 
      
       
       
    },

    textWarpScrollHandle(e) {
      console.log('l')  
      this.$refs.previewWarp.scrollTop = e.target.scrollTop
    },
    contentWarpScrollHandle(e) { 
      console.log('r')
      setTimeout(() => {
        if (e.target.scrollTop !== this.$refs.scrollWarp.scrollTop) {
          this.$refs.scrollWarp.scrollTop = e.target.scrollTop
        }
      }, 500)
    },
    keepLastIndex(obj) { 
      if (window.getSelection) { // ie11 10 9 ff safari
          obj.focus(); // 解决ff不获取焦点无法定位问题
          const range = window.getSelection(); // 创建range
          range.selectAllChildren(obj); // range 选择obj下所有子内容
          console.log('range', range)
          range.collapseToEnd(); // 光标移至最后
      } else if (document.selection) { // ie10 9 8 7 6 5
          const range = document.selection.createRange(); // 创建选择对象
          // var range = document.body.createTextRange();
          range.moveToElementText(obj); // range定位到obj
          range.collapse(false); // 光标移至最后
          range.select();
      }
    },
    getContent() {
      return this.$refs.previewWarp.innerHTML
    },
    test() {
      console.log(this.content)
    }
  },
  created() {
    this.content = this.value
  },
  mounted() { 
    const rendererMD = new marked.Renderer();
    marked.setOptions({
      renderer: rendererMD,
      gfm: true,
      tables: true,
      breaks: false,
      pedantic: false,
      sanitize: false,
      smartLists: true,
      smartypants: false,
      highlight: function (code) {
        return hljs.highlightAuto(code).value;
      }
    })
    
    this.$refs.editWarp.innerText = this.content
    this.$refs.previewWarp.innerHTML = marked(this.content).replace(/<pre>/gi, '<pre class="hljs">')
    
  },
  beforeDestroy() {
    this.inputTimer && clearTimeout(this.inputTimer)
  }
}
</script>


<style lang="scss" scoped>
@import "~@/style/_vars";
.markdown-warp { 
  height: 100%;
  overflow: hidden; 

}
.left-warp {
  height: 100%; 
  position: relative;
  float: left; 

  .edit-warp{
    width: 100%;
    height: 100%;
    padding: 15px;
    outline: none;
    /deep/ .img-text{
      color: red; // $blue-5;
    }
  }
}

.preview-warp {
  height: 100%;
  padding: 10px; 
  box-sizing: border-box;
  // overflow-x: hidden;
  overflow-y: auto;
    
}

.resize-save {
  position: absolute;
  top: 0; right: 5px; bottom: 0; left: 0; 
  overflow-x: hidden; 
}
.resize-bar {
  position: relative;
  width: 400px; 
  height:  100%;
  resize: horizontal;
  cursor: ew-resize;
  cursor: col-resize;
  opacity: 0;
  overflow:  scroll;
  
  &:hover ~ .resize-line,
  &:active ~ .resize-line {
    border-left: 1px dashed skyblue;
  }
  &::-webkit-scrollbar {
    position:absolute;
    width: 10px;
    height: 999999px;
  }
}
/* 拖拽线 */
.resize-line {
  position: absolute;
  right: 0; top: 0; bottom: 0;
  border-right: 2px solid #eee;
  border-left: 1px solid #bbb;
  pointer-events: none;
} 

/* Firefox只有下面一小块区域可以拉伸 */
@supports (-moz-user-select: none) {
  .resize-bar:hover ~ .resize-line,
  .resize-bar:active ~ .resize-line {
      border-left: 1px solid #bbb;
  }
  .resize-bar:hover ~ .resize-line::after,
  .resize-bar:active ~ .resize-line::after {
      content: '';
      position: absolute;
      width: 16px; height: 16px;
      bottom: 0; right: -8px;
      // background: url(./resize.svg);
      background-size: 100% 100%;
  }
}
</style>